package com.platform.feign.spring.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.platform.feign.spring.other.IMapInteractiveApi;
import com.platform.feign.spring.other.IUserFile;
import feign.*;
import feign.httpclient.ApacheHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author hgx
 */
@Configuration
public class FeignConfig {

    @Resource
    private PlatformFeignEncoder platformFeignEncoder;
    @Resource
    private PlatformFeignDecoder platformFeignDecoder;
    @Resource
    private SpringContract springContract;
    @Resource
    private PlatformFeignSlf4jLogger platformFeignSlf4jLogger;


    @Bean
    public IMapInteractiveApi mapInteractiveApi() {
        List<RequestInterceptor> requestInterceptors = new ArrayList<>();
        requestInterceptors.add(FeignRequestInterceptor());
        return getBuilder(requestInterceptors)
                .target(IMapInteractiveApi.class, "http://172.16.2.80:9010/api/interactive");
    }

    @Bean
    public IUserFile userFile() {
        List<RequestInterceptor> requestInterceptors = new ArrayList<>();
        requestInterceptors.add(FeignRequestInterceptor());
        return getBuilder(requestInterceptors)
                .target(IUserFile.class, "http://10.10.20.121:9002/file");
    }


    private Feign.Builder getBuilder(List<RequestInterceptor> requestInterceptors) {
        return Feign.builder()
                .contract(springContract)
                .encoder(platformFeignEncoder)
                .decoder(platformFeignDecoder)
                .client(new ApacheHttpClient())
                .logger(platformFeignSlf4jLogger)
                .logLevel(Logger.Level.FULL)
                .requestInterceptors(requestInterceptors) //超时配置
                .options(new Request.Options(60000, TimeUnit.MILLISECONDS, 60000, TimeUnit.MILLISECONDS, true))
                //重试机制
                .retryer(new Retryer.Default(5000, 5000, 3));
    }



    @Bean
    public FastJsonConfig platformFastJsonConfig() {
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                //List字段如果为null,输出为[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //字符类型字段如果为null,输出为"",而非null
                SerializerFeature.WriteNullStringAsEmpty,
                //Boolean字段如果为null,输出为false,而非null
                SerializerFeature.WriteNullBooleanAsFalse,
                //消除对同一对象循环引用的问题，默认为false（如果不配置有可能会进入死循环）
                SerializerFeature.DisableCircularReferenceDetect,
                //是否输出值为null的字段,默认为false。
                SerializerFeature.WriteMapNullValue
        );

        fastJsonConfig.setSerializeFilters((ValueFilter) (object, name, value) -> {
            if (null == value) return "";
            if (value instanceof BigDecimal) return value.toString();
            if (value instanceof Integer) return value.toString();
            if (value instanceof Boolean) return Boolean.parseBoolean(value.toString()) ? "1" : "0";

            return value;
        });

        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        SerializerFeature[] serializerFeatures = fastJsonConfig.getSerializerFeatures();

        if (serializerFeatures == null) {
            serializerFeatures = new SerializerFeature[]{SerializerFeature.PrettyFormat};
        } else {
            List<SerializerFeature> featureList = new ArrayList<>(Arrays.asList(serializerFeatures));
            featureList.add(SerializerFeature.PrettyFormat);
            serializerFeatures = featureList.toArray(serializerFeatures);
        }
        fastJsonConfig.setSerializerFeatures(serializerFeatures);
        return fastJsonConfig;
    }



    public RequestInterceptor FeignRequestInterceptor() {
        // 此处可以重写请求参数
        return (template -> {
//            byte[] bytes = template.body();
//            String s = new String(bytes, template.requestCharset());
//            MapPredictTripReqDto mapPredictTripReqDto = JSON.parseObject(s, MapPredictTripReqDto.class);
//            mapPredictTripReqDto.setFromLngLat("104.138932,31.777777");
//            String s1 = JSON.toJSONString(mapPredictTripReqDto);
//            byte[] bytes1 = s1.getBytes();
//            template.body(bytes1, template.requestCharset());
        });
    }




}
